
import { defineComponent, PropType, ref } from 'vue'

export const InputTsx = defineComponent({
  name: 'input-tsx',
  props: {
    modelValue: {
      type: Object,
      required: true,
      default: () => ({})
    }
  },
  emits: ['update:modelValue'],
  setup (props, context) {
    const onInput = (value: string) => context.emit('update:modelValue', value)

    return () => <a-input value={props.modelValue} onChange={(e: any) => onInput(e.target.value)}/>
  }
})

export const SelectTsx = defineComponent({
  name: 'select-tsx',
  props: {
    modelValue: {
      type: Object,
      required: true,
      default: () => ({})
    },
    request: {
      type: Function,
      default: () => {}
    },
    keys: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['update:modelValue'],
  setup (props, context) {
    const list = ref<{
      name: string,
      value: any,
      key: string
    }[]>([])

    props.request().then((r: {
      name: string,
      value: any,
      key: string
    }[]) => {
      const keysMap = new Map()

      const optionsKeys = Object.keys(props.keys)
      optionsKeys.forEach(key => keysMap.set(key, props.keys[key]))
      console.log('r:', r)

      if (optionsKeys.length !== 0) {
        list.value = r.map(item => {
          const _data = {}
          Object.keys(item).forEach(key => {
            _data[key] = [keysMap.get(key)]
          })
          return _data
        }) as any

        console.log('list.value:', list.value)
      } else {
        list.value = r
      }
    })

    const onInput = (value: string) => context.emit('update:modelValue', value)

    return () => (
      <a-select value={props.modelValue} onChange={(value: string) => onInput(value)}>
       {
          list.value && list.value.map(item => <a-select-option key={item.key} value={item.value}>{item.name}</a-select-option>)
       }
      </a-select>
    )
  }
})

export const TextareaTsx = defineComponent({
  name: 'textarea-tsx',
  props: {
    modelValue: {
      type: Object,
      required: true,
      default: () => ({})
    }
  },
  emits: ['update:modelValue'],
  setup (props, context) {
    const onInput = (value: string) => context.emit('update:modelValue', value)
    return () => <a-textarea value={props.modelValue} allow-clear onChange={(e: any) => onInput(e.target.value)}/>
  }
})
